<template>
  <div class="mod-config">
    <!-- 查询条件 -->
    <div class="search-form search_form" v-loading='loadingPage'>
      <el-form :model="searchForm" size="mini" label-position="right" class="demo-form-inline" label-width="110px"
               style="width: 100%;">
        <el-row :gutter="22">
          <el-col :span="3.5">
            <el-form-item label="考核部门" prop="deptId">
              <el-select v-model="searchForm.deptId" placeholder="请选择" style="width: 150px;" filterable clearable
              >
                <el-option
                  v-for="(item ,index) in  deptList"
                  :key="index"
                  :label="item.deptName"
                  :value="item.deptId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3.5">
            <el-form-item label="被考核部门" prop="bdeptId">
              <el-select v-model="searchForm.bdeptId" placeholder="请选择" style="width: 150px;" filterable clearable
              >
                <el-option
                  v-for="(it ,index) in deptBList"
                  :key="index"
                  :label="it.name"
                  :value="it.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3.5">
            <el-form-item label="指标名称：">
              <el-input v-model="searchForm.keywords" placeholder="请输入指标名称" style="width: 150px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3.5">
            <el-form-item label="考核类别：">
              <el-select v-model="searchForm.assetTypeId" placeholder="请选择" style="width: 150px;" filterable clearable
              >
                <el-option
                  v-for="(ite ,index) in  assetTypeList"
                  :key="index"
                  :label="ite.name"
                  :value="ite.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="状态：">
              <el-select v-model="searchForm.submitStatus" placeholder="请选择" style="width: 100px;" filterable clearable>
                <el-option
                  v-for="item in optionsStates"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="3.5">
            <el-form-item label="月份：" prop="createTime">
              <el-date-picker
                v-model="searchForm.createTime"
                type="month"
                value-format="yyyy-MM"
                placeholder="选择月">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="3.5" style="text-align:center;">
            <el-button size="mini" type="primary" @click="searchBtn">查询</el-button>
            <el-button size="mini" @click="emptyClick">清空</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-col :span="8" style="text-align:left;margin-bottom: 10px;">
        <el-button v-hasPermi="['/permission/depadd']" size="mini" type="primary" @click="addOrUpdateHandle()"
        >新增
        </el-button>
        <el-button v-hasPermi="['/permission/depsub']" size="mini" type="success" @click="submitForm"
                   :disabled="this.checkedArr.length<=0">提交
        </el-button>
        <el-button v-hasPermi="['/permission/depexport']" size="mini" type="info" @click="exportForm"
        >导出
        </el-button>
        <el-button v-hasPermi="['/permission/depsheet']" size="mini" type="success" @click="deptSheet">部门表格
        </el-button>
      </el-col>
    </div>
    <el-table
      :data="tableData"
      border
      v-loading="loading"
      @selection-change="handleSelectionChange"
      :row-key="bindRowKeys"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        reserve-selection="reserve-selection"
        :selectable="selectable"
        width="50">
      </el-table-column>
      <el-table-column
        prop="bdeptName"
        header-align="center"
        align="center"
        label="被考核部门名称"
        width="130">
      </el-table-column>
      <el-table-column
        prop="deptName"
        header-align="center"
        align="center"
        label="考核部门名称"
        width="130">
      </el-table-column>
      <el-table-column
        prop="assetType"
        header-align="center"
        align="center"
        label="考核类别"
      >
      </el-table-column>
      <el-table-column
        prop="indicatorTaskName"
        header-align="center"
        align="center"
        label="指标名称">
      </el-table-column>
      <el-table-column
        prop="complete"
        header-align="center"
        align="center"
        label="完成情况">
      </el-table-column>
      <el-table-column
        prop="assessRuleScore"
        header-align="center"
        align="center"
        label="考核规则得分">
      </el-table-column>

      <el-table-column
        prop="totalScore"
        header-align="center"
        align="center"
        label="总得分">
      </el-table-column>

      <el-table-column
        prop="submitStatus"
        header-align="center"
        align="submitStatus"
        label="状态">
        <template slot-scope="scope">
          <span style="color: #999999 ;font-weight:bold" v-if="scope.row.submitStatus === 0">未提交</span>
          <span style="color: #049EDC;font-weight:bold" v-if="scope.row.submitStatus === 1">已提交</span>
          <span style="color: #ff4949; font-weight:bold" v-if="scope.row.submitStatus === 2">已驳回</span>
          <span style="color: gold ;font-weight:bold" v-if="scope.row.submitStatus === 3">已申诉</span>
          <span style="color: aquamarine ;font-weight:bold" v-if="scope.row.submitStatus === 4">已同意</span>
          <span style="color: #13ce66 ;font-weight:bold" v-if="scope.row.submitStatus === 5">完成</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        header-align="center"
        align="center"
        label="备注">
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        label="创建时间"
        width="150">
        <template slot-scope="scope">
          {{ new Date(scope.row.createTime).toLocaleDateString().replaceAll('/', '-') }}
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="130"
        label="操作">
        <template slot-scope="scope">
          <el-button 修改 v-hasPermi="['/permission/depupdate']" type="text" size="small"
                     v-if="scope.row.submitStatus === 0 || scope.row.submitStatus === 4"
                     @click="addOrUpdateHandle(scope.row.id)">修改
          </el-button>
          <el-button 申诉 v-hasPermi="['/permission/depappeal']" type="text" size="small"
                     v-if="scope.row.submitStatus===2 || scope.row.submitStatus===5"
                     @click="appeal(scope.row)">申诉
          </el-button>

          <el-button 审批记录 type="text" size="small"
                     v-if="scope.row.submitStatus===2 || scope.row.submitStatus===4 ||scope.row.submitStatus===5"
                     @click="approval(scope.row)">审批记录
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <div class="progress_lok_page">
      <page
        :hidden="tableData && tableData.length === 0"
        :total="total"
        :page.sync="page"
        :limit.sync="pageSize"
        @pagination="handlePageChange"/>
    </div>
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getList"></add-or-update>

    <el-dialog
      :title="'申诉'"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form :model="sensuForm" :rules="sensuRule" ref="sensuForm" @keyup.enter.native="sensuFormSubmit()"
               label-width="80px">
        <el-form-item label="申诉人" prop="appealUser">
          <el-input v-model="sensuForm.appealUser" disabled></el-input>

        </el-form-item>
        <el-form-item label="联系方式" prop="contactNumber" style="margin: 14px 0;">
          <el-input v-model="sensuForm.contactNumber" placeholder="请输入联系方式"></el-input>
        </el-form-item>

        <el-form-item label="申诉描述" prop="description">
          <el-input type="textarea" v-model="sensuForm.description" placeholder="请输入申诉描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="sensuFormSubmit()">提交</el-button>
        </span>
    </el-dialog>


    <el-dialog
      :title="'审批记录'"
      :close-on-click-modal="false"
      :visible.sync="approvalVisible">
      <el-table :data="tableList" border>
        <el-table-column property="auditUserName" label="审批人" width="170" align="center"></el-table-column>
        <el-table-column property="auditResult" label="审批结果" width="170" align="center"></el-table-column>
        <el-table-column property="createTime" label="审批时间" width="200" align="center">
        </el-table-column>
        <el-table-column property="auditOpinion" label="审批意见" align="center"></el-table-column>

      </el-table>
    </el-dialog>
  </div>

  <!-- 弹窗, 新增 / 修改 -->
</template>

<script>
  import AddOrUpdate from './depperformance-add-or-update'
  import axios from 'axios'
  import { Encrypt } from '../../utils/cryptoAES'
  import { AesDecrypt } from '../../utils/AesDecrypt'

  export default {
    data() {
      return {
        importLoading: false,
        approveLoading: false,
        showform: false,
        addOrUpdateVisible: false,
        approvalVisible: false,
        tableList: [],// 审批记录
        visible: false,
        tableData: [],
        fileList: [],
        assetTypeList: [],
        loadingPage: true,
        loading: true,
        currentPage: 0,
        page: 1,
        pageSize: 10,
        total: 0,
        checkedArr: [],//要导出的数据数组
        searchForm: {
          keywords: '',//搜索条件
          ids: [],//导出数据集合 空为全部
          deptId: null,
          bdeptId: null,
          assetTypeId: null,
          submitStatus: null,
          createTime: null
        },
        deptList: [],
        deptBList: [],
        rowDeptId: '',
        rulesList: [],
        standarDList: [],
        optionsStates: [{
          value: -1,
          label: '全部'
        }, {
          value: 0,
          label: '未提交'
        }, {
          value: 1,
          label: '已提交'
        }, {
          value: 2,
          label: '已驳回'
        }, {
          value: 3,
          label: '已申诉'
        }, {
          value: 4,
          label: '已同意'
        }, {
          value: 5,
          label: '完成'
        }
        ],
        // 申诉
        sensuForm: {
          deptPerformanceId: '',
          appealUserId: null,
          appealUser: null,
          // appealType: null,
          contactNumber: null,
          description: null,
          appealDept: null,
          appealDeptId: null
        },
        // 申诉校验
        sensuRule: {
          contactNumber: [
            { required: true, message: '联系方式不能为空', trigger: 'blur' }
          ],
          description: [
            { required: true, message: '申诉描述不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    components: {
      AddOrUpdate
    },
    created() {
      var today = new Date ()
      var year = today.getFullYear ()//获取年份
      var month = today.getMonth () + 1//获取月份
      var monthOne = (month < 10) ? ('0' + month) : month
      this.searchForm.createTime = year + '-' + monthOne

      // 被考核部门
      this.getDeptBList ()
      this.getDeptList ()
      // 获得考核类别
      this.getAssetTypeList ()
      this.getList ()

    },

    methods: {
      // 获取列表
      getList() {
        var st
        if (this.searchForm.submitStatus == null) {
          this.searchForm.submitStatus = -1
        }
        var uu = {
          page: this.page,
          pageSize: this.pageSize,
          keywords: this.searchForm.keywords,//部门
          assetDeptId: this.searchForm.deptId,
          deptId: this.searchForm.bdeptId,
          status: this.searchForm.submitStatus,
          assetTypeId: this.searchForm.assetTypeId,
          createTime: this.searchForm.createTime
        }
        var jsonString = JSON.stringify (uu)
        var yy = Encrypt (jsonString)
        var encodedString = encodeURIComponent (yy)
        axios ({
          method: 'post',
          url: '/hr-xc-human-resources-perform-manage/generator/depperformance/list',
          data: encodedString
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            var data = AesDecrypt (data.result)
            this.tableData = data.result.content
            this.total = data.result.total
            this.loading = false
            this.loadingPage = false
          } else {
            this.loading = false
            this.loadingPage = false
            this.$message.error (data.msg)
            this.tableData = []
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },
      // 查询部门
      getDeptList() {
        axios ({
          method: 'post',
          url: '/hr-xc-human-resources-perform-manage/generator/deptexaminelrules/queryAllAssetDept'
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            this.deptList = data.result
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },
// 导出
      async exportForm() {
        this.loadingPage = true
        this.searchForm.ids = []
        if (this.checkedArr.length != 0) {
          this.checkedArr.forEach (item => {
            this.searchForm.ids.push (item.id)
          })
        } else {
          this.ids = []
        }
        axios ({
          method: 'post',
          responseType: 'blob',
          url: '/hr-xc-human-resources-perform-manage/generator/depperformance/export',
          data: {
            ids: this.searchForm.ids,
            keywords: this.searchForm.keywords,//部门
            assetDeptId: this.searchForm.deptId,
            deptId: this.searchForm.bdeptId,
            status: this.searchForm.submitStatus,
            assetTypeId: this.searchForm.assetTypeId,
            createTime: this.searchForm.createTime
          }
        }).then (({ data }) => {
          if (data.size) {
            const downloadElement = document.createElement ('a')
            const href = window.URL.createObjectURL (data) // 创建下载的链接
            downloadElement.href = href
            downloadElement.download = decodeURI ('部门绩效办公室.xls') // 下载后文件名
            document.body.appendChild (downloadElement)
            downloadElement.click () // 点击下载
            document.body.removeChild (downloadElement) // 下载完成移除元素
            window.URL.revokeObjectURL (href) // 释放掉blob对象
            this.loadingPage = false
            // this.$my_message.success ('导出成功')
            this.$message.success ('导出成功')
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },
      // 提交
      submitForm() {
        this.ids = []
        if (this.checkedArr.length != 0) {
          this.checkedArr.forEach (item => {
            this.ids.push (item.id)
          })
        } else {
          this.ids = []
        }
        if (this.ids.length <= 0) {
          return this.$message.warning ('请先选中！')
        }
        axios ({
          method: 'post',
          url: '/hr-xc-human-resources-perform-manage/generator/depperformance/batchSubmit',
          data: {
            ids: this.ids
          }
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            if (data.success) {
              this.$message.success ('提交成功')
            } else {
              this.$message.error ('提交失败')
            }
            this.getList ()
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },

      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$nextTick (() => {
          this.$refs.addOrUpdate.init (id)
        })
      },
      // 查询
      searchBtn() {
        this.loading = true
        this.page = 1
        this.getList ()
      },
      /** 点击分页触发的事件 */
      handlePageChange(pageInfo) {
        this.loading = true
        this.page = pageInfo.page
        this.pageSize = pageInfo.limit
        this.getList ()
      },
      // 清空
      emptyClick() {
        this.searchForm.keywords = ''
        this.searchForm.deptId = ''
        this.searchForm.bdeptId = ''
        this.searchForm.assetTypeId = ''
        this.searchForm.status = -1
        this.searchForm.createTime = ''
      },

      bindRowKeys(row) {
        return row.id
      },
      // 多选
      handleSelectionChange(value) {

        this.checkedArr = value
        // element表格多选第一页选中往后翻一页全选，再回到第一页会再次选中第一页的数据，所以需要手动去重
        let hash = {}
        this.checkedArr = this.checkedArr.reduce ((preVal, curVal) => {
          hash[curVal.id] ? '' : hash[curVal.id] = true && preVal.push (curVal)
          return preVal
        }, [])
      },
      // 申诉
      appeal(row) {
        this.visible = true
        this.sensuForm.deptPerformanceId = row.id
        this.sensuForm.appealDept = row.bdeptName
        this.sensuForm.appealDeptId = row.bdeptId
        // 获得当前登录人
        this.getUsers ()

      },
      // 申诉提交
      sensuFormSubmit() {
        this.$refs['sensuForm'].validate ((valid) => {
          if (valid) {
            var uu = {
              deptPerformanceId: this.sensuForm.deptPerformanceId,
              appealUserId: this.sensuForm.appealUserId,
              appealUser: this.sensuForm.appealUser,
              // appealType: this.sensuForm.appealType,
              contactNumber: this.sensuForm.contactNumber,
              description: this.sensuForm.description,
              appealDept: this.sensuForm.appealDept,
              appealDeptId: this.sensuForm.appealDeptId
            }
            var jsonString = JSON.stringify (uu)
            var yy = Encrypt (jsonString)
            var encodedString = encodeURIComponent (yy)

            axios ({
              method: 'post',
              url: '/hr-xc-human-resources-perform-manage/generator/depperformance/appeal',
              data: encodedString
            }).then (({ data }) => {
              if (data && data.code === '00000') {
                this.$message ({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.getList ()
                  }
                })
              } else {
                this.loading = false
                this.loadingPage = false
                this.$message.error (data.msg)
              }
            }).catch (error => {
              this.$message.error ('服务器访问异常，请从新登录')
            })
          }
        })
      },
      handleSelect(v) {
        this.standarDList = []
        axios ({
          url: `/hr-xc-human-resources-perform-manage/generator/deptexaminelrules/queryStandard`,
          method: 'post',
          data: {
            'deptId': this.rowDeptId,
            'rule': v
          }
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            data.result.forEach (v => {
              this.standarDList.push (v)
            })

          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },

      addItem() {
        this.dafenForm.dynamicItem.push ({})
      },
      deleteItem(item, index) {
        this.dafenForm.dynamicItem.splice (index, 1)
      },

      getUsers() {
        let that = this
        axios ({
          url: '/hr-xc-human-resources-perform-manage/authUser/getCurrentUser',
          method: 'get'
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            var data = AesDecrypt (data.result)
            that.sensuForm.appealUserId = data.userId
            that.sensuForm.appealUser = data.userName
          } else {
            that.$message.error ('获得当前登录人失败！')
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },
      getLable(val) {
        let dir = this.auditUserList.find ((item) => item.id === val)
        this.sensuForm.appealUser = dir.name
      },
      selectable(row, index) {
        if (row.submitStatus === 0 || row.submitStatus === 4) {
          return true
        } else {
          return false
        }
      },
      // 跳转到部门表格
      deptSheet() {
        this.$router.push ({
          path: '/depperformanceMenu/depchart',
          query: {}
        })
      },

      getAssetTypeList() {
        axios ({
          method: 'post',
          url: '/hr-xc-human-resources-perform-manage/generator/depperformance/queryAllDeptCategory'
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            var data = AesDecrypt (data.result)
            this.assetTypeList = data
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },
      // 查询被考核部门
      getDeptBList() {
        axios ({
          method: 'post',
          url: '/hr-xc-human-resources-perform-manage/generator/torgdept/queryAllDeptIdAndName'
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            var data = AesDecrypt (data.result)
            this.deptBList = data
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },
      // 审批记录
      approval(row) {
        // TODO: 预留查询审批记录
        this.approvalVisible = true
        axios ({
          method: 'get',
          url: '/hr-xc-human-resources-perform-manage/generator/depappealform/queryAuditForm/' + row.id
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            if (data.result.length > 0) {
              var data = AesDecrypt (data.result)
              this.tableList = data
            }
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      }
    }
  }
</script>
